<?php
namespace app\commands;



use app\modules\common\components\Eureka;
use Yii;
use yii\console\Controller;
use yii\helpers\FileHelper;

class EurekaController extends Controller
{
    private static $registerPidFile = "";


    public function __construct($id, $module, $config = [])
    {
        self::$registerPidFile = Yii::getAlias('@runtime')."/log/eureka_register.pid";
        $pidDir = dirname(self::$registerPidFile);
        if(!file_exists($pidDir)){
            FileHelper::createDirectory($pidDir);
        }

        parent::__construct($id, $module, $config);
    }

    /**
     * 注册eureka
     */
    public function actionRegister()
    {
        if($this->getPid(self::$registerPidFile) !== false)
        {
            $this->stdout("eurekaRegister already start".PHP_EOL);
            exit(1);
        }

        $pid = pcntl_fork();
        if($pid == -1)
        {
            //创建子进程错误
            $this->stdout("cloud not fork".PHP_EOL);
        }else if($pid){
            file_put_contents(self::$registerPidFile,$pid);
        }else{
            //进行eureka操作

            $eureka = Eureka::getInstance("UP");
            $client = $eureka->getEurekaClient();

            $client->start();
        }
    }

    /**
     * 取消注册
     */
    public function actionStop()
    {
        $this->sendRegisterSignal(SIGTERM);

        //进行eureka取消操作
        $eureka = Eureka::getInstance("DOWN");
        $client = $eureka->getEurekaClient();
        $client->deRegister();

        $this->stdout("eurekaRegister is stopped".PHP_EOL);

    }


    private function sendRegisterSignal($sig)
    {
        if ($pid = $this->getPid(self::$registerPidFile)) {
            posix_kill($pid, $sig);
        } else {
            $this->stdout("server is not running!" . PHP_EOL);
            exit(1);
        }
    }

    private function getPid($pidFile)
    {
        if (file_exists($pidFile)) {
            $pid = file_get_contents($pidFile);
            if (posix_getpgid($pid)) {
                return $pid;
            } else {
                unlink($pidFile);
            }
        }
        return false;
    }

}